package madoop.reign;

import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class Mission
{
    protected Platform    platform;
    protected Application application;
    protected Process     process;
    protected DataInput   input;
    protected DataOutput  output;
    protected int         port;


    public Mission(Platform platform, int port, Application application)
    {
        this.platform = platform;
        this.application = application;
        this.port = port;
    }


    public void launch() throws IOException
    {
        ProcessBuilder pb = new ProcessBuilder();
        List<String> commands = new ArrayList<String>();
        commands.add("java");
        commands.add("-cp");
        StringBuilder classpath = new StringBuilder();
        classpath.append(application.classpath);
        for (String cp : platform.classpath) {
            classpath.append(':').append(cp);
        }
        commands.add(classpath.toString());
        commands.add(platform.main);
        for (String arg : platform.arguments) {
            commands.add(arg);
        }
        pb.command(commands);
        Map<String, String> env = pb.environment();
        env.put("platform.port", Integer.toString(platform.port));
        env.put("application.name", application.name);
        process = pb.start();
        input = new DataInputStream(process.getInputStream());
        output = new DataOutputStream(process.getOutputStream());
    }


    public boolean isOver()
    {
        if (process == null)
            return false;
        try {
            process.exitValue();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
